/**
 * Copyright 厦门中软海晟信息技术有限公司 版权所有 违者必究 2019
 */
package com.leetCode;

/**
 * @author : sunzb
 * @date: 2019/5/15
 */
public class _22_208_ImplementTrie_PrefixTree {

    public static class TrieNode {
        public char val;
        public boolean isWord;
        public TrieNode[] children = new TrieNode[26];
        public TrieNode() {}

        TrieNode(char c) {
            TrieNode node = new TrieNode();
            node.val = c;
        }
    }

    private TrieNode root;

    /** Initialize your data structure here. */
    public _22_208_ImplementTrie_PrefixTree() {
        root = new TrieNode();
        root.val = ' ';
    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode ws = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            int index = c - 'a';
            if (ws.children[index] == null) {
                ws.children[index] = new TrieNode(c);
            }
            ws = ws.children[index];
        }
        ws.isWord = true;
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode ws = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            int index = c - 'a';
            if (ws.children[index] == null) return false;
            ws = ws.children[index];
        }
        return ws.isWord;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode ws = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            int index = c - 'a';
            if (ws.children[index] == null) return false;
            ws = ws.children[index];
        }
        return true;
    }

    public static void main(String[] args) {
        _22_208_ImplementTrie_PrefixTree trie = new _22_208_ImplementTrie_PrefixTree();
        trie.insert("apple");
        System.out.println(trie.search("apple"));   // returns true
        System.out.println(trie.search("app"));     // returns false
        System.out.println(trie.startsWith("app")); // returns true
        trie.insert("app");
        System.out.println(trie.search("app"));     // returns true
        trie.insert("abcdef");
        trie.insert("ccd");
        System.out.println(trie.search("ccd")); // returns true
        System.out.println(trie.startsWith("abc")); // returns true
    }
}
